<template>
  <div class="game-wrap">
    <div class="title-row">
      <img class="game-title" :src="title" alt="" />
    </div>
    <div class="question">
      <div class="top">
        <!-- 第几关 -->
        <div
          id="header"
          style="height: 1rem;width: 10rem; text-align: center;line-height: 1rem;display: none"
          onclick="localStorage.setItem('peotry_stage',1)"
        >
          第1关
        </div>
        <!-- <img style="width: 100%;padding-top: 80px;" :src="answer" alt=""> -->
        <div
          id="plate"
          style="background: #FFF9EB"
        ></div>
      </div>
      <div class="difficulty">
        <span>难度：</span>
        <span
          v-for="item in difficultyData"
          :key="item.value"
          :class="
            currDiff === item.value
              ? 'difficulty-item active'
              : 'difficulty-item'
          "
          @click="currDiff = item.value"
          >{{ item.label }}</span
        >
      </div>
      <div class="options">
        <div class="tips">
          <span>请选择</span>
          <span @click="handleExplain">
            <SvgIcon icon-class="explain" class="explain" />
            游戏说明
          </span>
        </div>
        <div id="answer" class="answer">
          <!-- <span
            v-for="item in answerData"
            :key="item.value"
            class="answer-item"
            >{{ item.label }}</span
          > -->
          <div></div>
        </div>
        <div class="operation">
          <img
            class="publish-btn"
            :src="publish"
            alt=""
            @click="handleConfirmAnswer"
          />
          <img class="reset-btn" :src="reset" alt="" />
        </div>
      </div>
      <div class="back-row">
        <span @click="handleBack">
          <SvgIcon icon-class="back-btn" class="back-icon" />
          <em class="back-text">返回</em>
        </span>
      </div>
      <!-- 答題結果 -->
      <Dialog
        :visible="visible"
        :header="true"
        :btnBg="btnBg"
        @close="handleClose"
        @confirm="handleConfirm"
      >
        <div class="dialog-container">
          <img style="width: 16vw" :src="correct" alt="" />
          <p class="answer-text">{{ answerText }}</p>
        </div>
      </Dialog>
      <!-- 遊戲說明 -->
      <Dialog
        :visible="explainVisible"
        :header="false"
        :btnBg="confirmBg"
        @close="handleCloseExplain"
        @confirm="handleConfirmExplain"
      >
        <div class="dialog-container">
          <div class="explain-wrap">
            <img class="explain-img" :src="explain" alt="" />
          </div>
        </div>
      </Dialog>
    </div>
  </div>
</template>

<script>
import { SvgIcon, Dialog } from "@/components";
import stageArr from "@/data/stageArr";

export default {
  components: {
    SvgIcon,
    Dialog
  },
  data() {
    return {
      title: require("@/assets/game/proverb_game_title.png"),
      publish: require("@/assets/game/publish.png"),
      reset: require("@/assets/game/reset.png"),
      confirmBg: require("@/assets/game/confirm_btn.png"),
      conturnBg: require("@/assets/game/conturn.png"),
      resetBg: require("@/assets/game/reset_btn.png"),
      correct: require("@/assets/game/correct.png"),
      error: require("@/assets/game/error.png"),
      explain: require("@/assets/game/explain.png"),
      answer: require("@/assets/game/answer-item.png"),
      btnBg: "",
      answerResultImg: "",
      difficultyData: [
        { label: "简单", value: 0 },
        { label: "中等", value: 1 },
        { label: "难", value: 2 }
      ],
      answerData: [
        { label: "豪", value: 0 },
        { label: "牛", value: 1 },
        { label: "走", value: 2 },
        { label: "不", value: 3 },
        { label: "豪", value: 4 }
      ],
      currDiff: 0,
      visible: false,
      answerText: "恭喜您答对了",
      explainVisible: false,
      // 游戏数据
      matrix: {},
      idiom_dic: {},
      block_num: 10,
      block_size: 0,
      hide_arr: [],
      select_rect: [-1, -1],
      border_width: 0.04,
      stage: 0,
      stage_arr: stageArr,
      run_dire: 0,
      tc: 3
    };
  },
  mounted() {
    this.handleInitPage();
  },
  methods: {
    // 进入页面执行初始化
    handleInitPage() {
      let his_stage = localStorage.getItem("protry_stage");
      if (his_stage != null) {
        this.stage = parseInt(his_stage) - 1;
      }
      let documentWidth = window.screen.availWidth;
      this.block_size = 9.0 / this.block_num;

      this.load_next_stage();

      document.documentElement.style.fontSize = documentWidth / 10 + "px";
      document.getElementById("header").style.fontSize = "0.6rem";
    },
    // 查看說明
    handleExplain() {
      this.explainVisible = true;
    },
    // 關閉說明
    handleCloseExplain() {
      this.explainVisible = false;
    },
    // 知道了
    handleConfirmExplain() {
      this.explainVisible = false;
    },
    // 關閉
    handleClose() {
      this.visible = false;
      this.btnBg = "";
      this.answerResultImg = "";
      this.answerText = "";
    },
    // 確定
    handleConfirm() {
      this.visible = false;
    },
    // 點擊完成
    handleConfirmAnswer() {
      this.answerResultImg = this.confirmBg;
      this.answerText = "恭喜您答对了";
      this.btnBg = this.conturnBg;
      this.visible = true;
    },
    // 返回
    handleBack() {
      this.$router.back();
    },

    // 游戏逻辑部分
    // 初始化
    rand_int(minNum, maxNum) {
      return parseInt(Math.random() * (maxNum - minNum) + minNum);
    },
    // 获取
    matrix_get_val(x, y) {
      return this.matrix.data[y * this.matrix.cols + x];
    },
    // 设置
    matrix_set_val(x, y, val) {
      this.matrix.data[y * this.matrix.cols + x] = val;
    },
    // 周围是否存在
    exist_val_four_around(x, y, self_x, self_y) {
      const move_arr = [(-1, 0), (1, 0), (0, -1), (0, 1)];
      for (let i = 0; i < move_arr.length; i++) {
        let tmp = move_arr[i];
        let dx = tmp[0];
        let dy = tmp[1];
        let tx = x + dx;
        let ty = y + dy;
        if (tx === self_x && ty === self_y) continue;
        if (
          tx < 0 ||
          tx >= this.matrix.cols ||
          ty < 0 ||
          ty >= this.matrix.rows
        )
          continue;
        if (this.matrix.data[ty * self.cols + tx]) return 1;
      }
      return 0;
    },
    // 获取成语信息数组
    get_idiom_info_arr(x, y) {
      let idiom_info_arr = [];
      for (let idiom in this.idiom_dic) {
        let idiom_info = this.idiom_dic[idiom];
        for (let i = 0; i < idiom_info.word_arr.length; i++) {
          let word_info = idiom_info.word_arr[i];
          if (word_info.i === x && word_info.j === y) {
            idiom_info_arr.push(idiom_info);
            break;
          }
        }
      }
      return idiom_info_arr;
    },
    // 加载
    load_stage() {
      let stage_data = this.stage_arr[this.stage - 1];
      this.block_num = stage_data.block_num;
      this.matrix = {};
      this.matrix.cols = this.block_num;
      this.matrix.rows = this.block_num;
      this.matrix.data = [];
      for (let i = 0; i < this.block_num * this.block_num; i++) {
        this.matrix.data.push(null);
      }
      this.idiom_dic = {};
      let stage_idiom_arr = stage_data.idiom_arr.split(";");
      for (let i = 0; i < stage_idiom_arr.length; i++) {
        let idiom_paras = stage_idiom_arr[i].split(",");
        let idiom = idiom_paras[0];
        let dire = parseInt(idiom_paras[1]);

        this.idiom_dic[idiom] = {};
        this.idiom_dic[idiom].word_arr = [];
        this.idiom_dic[idiom].dire = dire;

        let word_arr = idiom_paras[2].split("|");
        for (let j = 0; j < word_arr.length; j++) {
          var word_paras = word_arr[j].split(" ");
          var x = parseInt(word_paras[0]);
          var y = parseInt(word_paras[1]);
          var word = word_paras[2];
          if (this.matrix_get_val(x, y) == null) {
            let word_info = {};
            word_info.word = word;
            word_info.i = x;
            word_info.j = y;
            word_info.is_lock = true;
            this.matrix_set_val(x, y, word_info);
            this.idiom_dic[idiom].word_arr.push(word_info);
          } else {
            let word_info = this.matrix_get_val(x, y);
            this.idiom_dic[idiom].word_arr.push(word_info);
          }
        }
      }

      this.hide_arr = [];
      let stage_hide_arr = stage_data.hide_arr.split(";");
      for (let i = 0; i < stage_hide_arr.length; i++) {
        let hide_paras = stage_hide_arr[i].split(" ");
        let x = parseInt(hide_paras[0]);
        let y = parseInt(hide_paras[1]);
        let word = hide_paras[2];

        let info = this.matrix_get_val(x, y);
        info.word = "";
        info.hide_index = this.hide_arr.length;
        info.is_lock = false;

        this.hide_arr.push([x, y, word, null, null]);
      }

      this.select_rect = null;
      for (let i = 0; i < this.block_num; i++) {
        for (let j = 0; j < this.block_num; j++) {
          let word_info = this.matrix_get_val(i, j);
          if (word_info && word_info.word == "") {
            this.select_rect = [i, j];
            break;
          }
        }
        if (this.select_rect) break;
      }
      this.run_dire = this.get_idiom_info_arr(
        this.select_rect[0],
        this.select_rect[1]
      )[0].dire;

      this.init_game();
      this.refresh_bg();
      document.getElementById("header").innerText = `第${this.stage}关`;
      localStorage.setItem("peotry_stage", this.stage);
    },
    // 加载上一题
    load_prev_stage() {
      this.stage = this.stage - 1;
      this.load_stage();
    },
    // 加载下一题
    load_next_stage() {
      this.stage = this.stage + 1;
      this.load_stage();
    },
    // 设置文字选中
    set_word_select(x, y) {
      this.select_rect = [x, y];
      let info = this.matrix_get_val(x, y);
      info.div.className = "word select";
    },
    // 检测是否成功
    check_success() {
      for (let idiom in this.idiom_dic) {
        let idiom_info = this.idiom_dic[idiom];
        let word_arr = idiom_info.word_arr;
        for (let i = 0; i < word_arr.length; i++) {
          let word_info = word_arr[i];
          if (word_info.state != 1) word_info.state = 0;
        }
      }

      for (let idiom in this.idiom_dic) {
        let idiom_info = this.idiom_dic[idiom];
        let tmp_idiom_str = "";
        let word_arr = idiom_info.word_arr;
        for (let i = 0; i < word_arr.length; i++) {
          let word_info = word_arr[i];
          if (word_info.word.length > 0) tmp_idiom_str += word_info.word;
        }
        let state = 0;
        if (tmp_idiom_str.length == idiom.length) {
          state = tmp_idiom_str == idiom ? 1 : 2;
        }

        for (let i = 0; i < word_arr.length; i++) {
          let word_info = word_arr[i];
          if (word_info.state != 1) {
            if (state != 0 || word_info.state != 2) word_info.state = state;
          }
        }
      }

      for (var idiom in this.idiom_dic) {
        var idiom_info = this.idiom_dic[idiom];
        var word_arr = idiom_info.word_arr;
        for (var i = 0; i < word_arr.length; i++) {
          var word_info = word_arr[i];
          if (word_info.state != 1) return false;
        }
      }

      return true;
    },
    // 检查相同的成语
    check_same_idiom(x, y) {
      for (let idiom in this.idiom_dic) {
        let word_arr = this.idiom_dic[idiom].word_arr;
        let contain_word = false;
        for (let i = 0; i < word_arr.length; i++) {
          let word_info = word_arr[i];
          if (word_info.i == x && word_info.j == y) {
            contain_word = true;
            break;
          }
        }
        if (contain_word) {
          for (let i = 0; i < word_arr.length; i++) {
            let word_info = word_arr[i];
            if (word_info.word.length == 0) {
              this.set_word_select(word_info.i, word_info.j);
              return true;
            }
          }
        }
      }
      return false;
    },
    // 获取相同成语信息
    get_same_dire_idiom_info(x, y) {
      let idiom_info_arr = this.get_idiom_info_arr(x, y);
      for (let i = 0; i < idiom_info_arr.length; i++) {
        let idiom_info = idiom_info_arr[i];
        if (idiom_info.dire == this.run_dire) {
          return idiom_info;
        }
      }
      return null;
    },
    // 制作下一个选中
    make_next_select() {
      let x = this.select_rect[0];
      let y = this.select_rect[1];

      let idiom_info = this.get_same_dire_idiom_info(x, y);
      if (idiom_info) {
        for (let i = 0; i < idiom_info.word_arr.length; i++) {
          let word_info = idiom_info.word_arr[i];
          if (word_info.word.length == 0) {
            this.set_word_select(word_info.i, word_info.j);
            return;
          }
        }
      }

      this.select_rect = null;
      for (let i = 0; i < this.block_num; i++) {
        for (let j = 0; j < this.block_num; j++) {
          var word_info = this.matrix_get_val(i, j);
          if (word_info && word_info.word == "") {
            this.select_rect = [i, j];
            break;
          }
        }
        if (this.select_rect) break;
      }
      if (this.select_rect) {
        this.set_word_select(this.select_rect[0], this.select_rect[1]);
        this.run_dire = this.get_idiom_info_arr(
          this.select_rect[0],
          this.select_rect[1]
        )[0].dire;
      }
    },
    // 刷新背景
    refresh_bg() {
      let word_divs = document
        .getElementById("plate")
        .getElementsByClassName("word");
      for (let i = 0; i < word_divs.length; i++) {
        let word_div = word_divs[i];
        let xy = word_div.dataV.split(",");
        let x = parseInt(xy[0]);
        let y = parseInt(xy[1]);
        let word_info = this.matrix_get_val(x, y);
        if (word_info.state == 1) word_div.style.color = "#191";
        else if (word_info.state == 2) word_div.style.color = "#f00";
        else if (word_info.is_lock) {
          // word_div.style.background = "#ddd";
          word_div.style.color = "#97222A";
        } else {
          word_div.style.background = "#fff";
          word_div.style.color = "#000";
        }
      }
    },
    // 定时进入下一关
    timeout_load_next_stage() {
      this.tc--;
      document.getElementById("header").innerText =
        "挑战成功," + this.tc + "秒后进入第" + (this.stage + 1) + "关";
      if (this.tc <= 0) this.load_next_stage();
      else setTimeout(this.timeout_load_next_stage, 1000);
    },
    // 点击当前文字
    click_item(e) {
      let t = e.target.dataT;
      let old_select_info = this.matrix_get_val(
        this.select_rect[0],
        this.select_rect[1]
      );
      old_select_info.div.className = "word";
      if (t == "plate") {
        //if(e.target.innerText.length>0){
        let tmp = e.target.dataV.split(",");
        let i = parseInt(tmp[0]);
        let j = parseInt(tmp[1]);
        let info = this.matrix_get_val(i, j);
        if (info.state == 1) {
          this.set_word_select(this.select_rect[0], this.select_rect[1]);
          this.run_dire = this.get_idiom_info_arr(
            this.select_rect[0],
            this.select_rect[1]
          )[0].dire;
          return;
        }
        if (info.word.length > 0) {
          this.hide_arr[info.op_hide_index][2] = e.target.innerText;
          this.hide_arr[info.op_hide_index][3] = null;
          this.hide_arr[info.op_hide_index][4].innerText = e.target.innerText;
          info.word = "";
          info.div.innerText = "";
          this.check_success();
        }
        this.set_word_select(i, j);
        this.run_dire = this.get_idiom_info_arr(i, j)[0].dire;
        //}
      } else if (t == "answer") {
        if (e.target.innerText.length > 0) {
          let index = parseInt(e.target.dataV);
          this.hide_arr[index][2] = "";
          this.hide_arr[index][3] = this.select_rect;
          let info = this.matrix_get_val(
            this.select_rect[0],
            this.select_rect[1]
          );
          info.word = e.target.innerText;
          info.div.innerText = e.target.innerText;
          info.op_hide_index = index;
          this.hide_arr[index][4].innerText = "";
          this.make_next_select();
          if (this.check_success()) {
            document.getElementById("header").innerText =
              "挑战成功,3秒后进入第" + (this.stage + 1) + "关";
            this.tc = 3;
            setTimeout(this.timeout_load_next_stage, 1000);
          }
        }
      }
      this.refresh_bg();
    },
    // 初始化游戏
    init_game() {
      let plate = document.getElementById("plate");
      const answer = document.querySelector("#answer");
      while (plate.hasChildNodes()) {
        plate.lastChild && plate.removeChild(plate.lastChild);
      }
      for (let i = 0; i < this.block_num; i++) {
        for (let j = 0; j < this.block_num; j++) {
          let info = this.matrix_get_val(i, j);
          if (info) {
            let div = document.createElement("div");
            div.dataT = "plate";
            div.dataV = i + "," + j;
            div.className = "word";
            div.style.left =
              i * this.block_size + 0.5 + this.border_width + i * 0.1 + "rem";
            div.style.top =
              j * this.block_size + 1.5 + this.border_width + j * 0.1 + "rem";
            div.style.width = this.block_size - this.border_width * 2 + "rem";
            div.style.height = this.block_size - this.border_width * 2 + "rem";
            div.innerText = info.word;
            div.style.lineHeight =
              this.block_size - this.border_width * 2 + "rem";
            div.style.fontSize = this.block_size * 0.8 + "rem";
            div.style.textAlign = "center";
            if (info.word.length == 0) div.onclick = this.click_item;
            plate.appendChild(div);
            info.div = div;
          }
        }
      }

      while (answer.hasChildNodes()) {
        answer.lastChild && answer.removeChild(answer.lastChild);
      }
      let ans_line_num = 8;
      if (this.block_size * 8 > 9.0)
        ans_line_num = Math.floor((9.0 * 0.9) / this.block_size);
      let sps = 9.0 / ans_line_num;
      let bsize = sps * 0.8;
      for (var i = 0; i < this.hide_arr.length; i++) {
        let tmp = this.hide_arr[i];
        // let xi = tmp[0];
        // let yi = tmp[1];
        let word = tmp[2];
        // let op = tmp[3];

        let div = document.createElement("div");
        div.dataT = "answer";
        div.dataV = i;
        div.className = "word";
        // div.style.left =
        //   Math.floor(i % ans_line_num) * sps + 0.5 + sps * 0.1 + "rem";
        // div.style.top = '0'
          // Math.floor(i / ans_line_num) * sps + 0.5 + 10 + sps * 0.1 + "rem";
          // 答案选项
        div.style.width = bsize + "rem";
        div.style.height = bsize + "rem";
        div.style.border = "solid 1px #97222A";
        div.style.borderRadius = "3px";
        div.style.background = "#F7E5C0";
        div.style.color = "#97222A";
        div.style.display = "inline-flex";
        div.style.justifyContent = "center";
        div.style.alignItems = "center";
        div.innerText = word;
        div.style.lineHeight = bsize + "rem";
        div.style.fontSize = bsize * 0.8 + "rem";
        div.style.textAlign = "center";
        div.style.marginRight = '.2rem'
        div.style.position = 'relative'
        div.onclick = this.click_item;
        answer.appendChild(div);
        tmp[4] = div;
      }

      // 暂时不进行动态设置选项高度
      // document.getElementById("answer").style.height =
      //   Math.ceil(i / ans_line_num) * sps + 1 + "rem";

      let info = this.matrix_get_val(this.select_rect[0], this.select_rect[1]);
      info.div.className = "word select";
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../../styles/variables.less";

.game-wrap {
  width: 100vw;
  height: 100vh;
  background: url("../../../assets/game/game_bg.png") no-repeat;
  background-size: contain;
  overflow: hidden;
  .title-row {
    text-align: center;
    padding-top: 4vh;
    padding-bottom: 2vh;
    .game-title {
      width: 38.5vw;
    }
  }
  .top {
    height: 50vh;
  }
  .question {
    width: 86.6vw;
    height: 84.6vh;
    background: url("../../../assets/game/question_bg.png") no-repeat;
    background-size: cover;
    margin: 0 auto;
    box-sizing: border-box;
    padding: 30px;
    .tips {
      font-size: 24px;
      text-align: center;
      color: @text;
      padding: 1vh 0 2vh;
      position: relative;
      span {
        font-family: "KaiTi";
        &:first-child {
          font-weight: 700;
        }
        &:last-child {
          position: absolute;
          right: 0;
          top: 14px;
          font-size: 14px;
        }
      }
      .explain {
        margin-right: -5px;
      }
    }
  }
  .difficulty {
    padding-left: 0.3rem;
    span {
      font-size: 0.22rem;
      color: @text;
      display: inline-block;
      margin-right: 0.02rem;
      padding: 0.04rem;
      border: 1px solid transparent;
    }
    .active {
      border: 1px solid @text;
      border-radius: 3px;
    }
  }
  .options {
    border: 0.09rem solid @sub-title;
    box-sizing: border-box;
    padding: 0.15rem;
    border-radius: 0.08rem;
    background: #ffefcc;
    box-shadow: 0 0 0.24rem 0 rgba(0, 0, 0, 0.5) inset;
    .publish-btn {
      margin-right: 0.36rem;
    }
  }
  .operation {
    display: flex;
    justify-content: center;
    padding: 0.42rem 0 0.4rem;
  }
  .publish-btn,
  .reset-btn {
    width: 1.8rem;
  }
  .answer {
    position: relative;
    height: 1rem;
    text-align: center;
    overflow: hidden;
    // .answer-item {
    // display: inline-flex;
    // justify-content: center;
    // align-items: center;
    // width: 60px;
    // height: 60px;
    // padding: 2px;
    // border-radius: 2px;
    // border: 3px solid @text;
    // margin-right: 4px;
    // color: @text;
    // font-size: 28px;
    // &:last-child {
    //   margin-right: 0;
    // }
    // }
  }
  .back-row {
    text-align: center;
    color: #97222a;
    padding-top: 0.16rem;
    .back-icon {
      font-size: 0.36rem;
    }
    .back-text {
      margin-left: 0.1rem;
      font-size: 0.28rem;
      font-weight: 700;
    }
  }
  .dialog-container {
    padding-top: 0.6rem;
    text-align: center;
    .answer-text {
      text-align: center;
      font-size: 0.38rem;
      color: @text;
      padding: 0.6rem 0;
    }
    .explain-wrap {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 0 0.62rem 0.68rem;
    }
    .explain-img {
      width: 100%;
    }
  }
}
</style>

<style>
#plate {
  margin: 0.5rem 0.5rem 0rem 0.5rem;
}
#answer {
  /* margin: 0.5rem; */
}
.word {
  position: absolute;
  background: #fff;
  border: solid 0.04rem #97222a;
  border-radius: 3px;
}
.select {
  border: solid 0.04rem #97222a;
  background: #f7e5c0 !important;
}
</style>
